package NBU;

require 5.002;

use strict;
use Carp;

use NBU::Class;
use NBU::Media;
use NBU::Mount;
use NBU::Host;
use NBU::Schedule;
use NBU::Robot;
use NBU::StorageUnit;
use NBU::Job;
use NBU::Image;

BEGIN {
  use Exporter   ();
  use AutoLoader qw(AUTOLOAD);
  use vars       qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $AUTOLOAD);
  use vars	 qw($prefix);
  $VERSION =     '0.01';
  @ISA =         qw();
  @EXPORT =      qw($prefix);
  @EXPORT_OK =   qw();
  %EXPORT_TAGS = qw();
}

#
# Determine the path to the top of the NetBackup binaries
my $NBP = "/usr/openv";

#
# If we can execute them as is great, else insert sudo
my $sudo = (-x $NBP."/volmgr/bin/vmoprcmd") ? "" : "/usr/local/bin/sudo ";

#
# and provide the world with a handy dandy prefix
$prefix = $sudo.$NBP."/";

my ($me, $master, @servers);
sub loadClusterInformation {

  $me = "localhost";

  #
  # Find out my own name (as far as NetBackup is concerned anyway).
  open(PIPE, $prefix."netbackup/bin/bpclntcmd -self |");
  while (<PIPE>) {
    chop;
    if (/gethostname\(\) returned: ([\S]+)/) {
      $me = $1;
    }
  }
  close(PIPE);

  #
  # Probe around to determine the full set of servers in this NetBackup
  # environment.  First we use bpgetconfig to locate the master in this
  # environment.  Then we use the same program to get the master to re-
  # gurgitate the full list of servers.
  $master = $me;
  $me = NBU::Host->byName($me);
  open(PIPE, $prefix."netbackup/bin/admincmd/bpgetconfig -g ".$me->name." |");
  $_ = <PIPE>;  chop;
  if (/Client of ([\S]+)/) {
    $master = $1;
  }
  close(PIPE);
  $master = NBU::Host->byName($master);

  open(PIPE, $prefix."netbackup/bin/admincmd/bpgetconfig -M ".$master->name." |");
  while (<PIPE>) {
    if (/SERVER = ([\S]+)/) {
      my $serverName = $1;

      # This bit of ugly code removes duplicate servers
      # from the list.  Duplicate in the sense that
      # servers <host> and <host>.bkup are really the
      # same machine and should NOT both appear in the list!
      my @canonicalServers;
      foreach my $host (@servers) {
	my $hostName = $host->name;
	if ($hostName =~ /${serverName}.bkup/) {
	  $serverName = undef;
	  push @canonicalServers, $host;
	}
	elsif ($serverName =~ /${hostName}.bkup/) {
	}
	else {
	  push @canonicalServers, $host;
	}
      }
      @servers = @canonicalServers;
      if (defined($serverName)) {
	my $server = NBU::Host->byName($serverName);
	push @servers, $server
      }
    }
  }
  close(PIPE);
}

sub masters {
  my $Class = shift;

  loadClusterInformation() if (!defined($me));
  return ($master);
}

sub master {
  my $Class = shift;

  loadClusterInformation() if (!defined($me));
  return ($master == $me);
}

sub me {
  my $Class = shift;

  loadClusterInformation() if (!defined($me));
  return $me;
}

sub servers {
  my $Class = shift;

  loadClusterInformation() if (!defined($me));
  return @servers;
}

1;

__END__
